#include "server.h"

Server::Server(QString newName, int newPort)
{
	name = newName;
	port = newPort;
}

Server::~Server()
{
	if (sock != NULL)
		delete sock;
}

void Server::run()
{
	qDebug("Starting server");

	sock = new QTcpServer(this);
//	sock->listen(QHostAddress::Any, (quint16)port);
	sock->listen(QHostAddress("127.0.0.1"), (quint16)port);

	connect(sock, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));

	exec();
}

/**
  *	Handles a new connection, by performing the handshake procedure/s
  * and then adding the connection to the list of connections
  */
void Server::handleNewConnection()
{
	qDebug("Server has received a connection");

	while (sock->hasPendingConnections())
	{
		QTcpSocket *conn = sock->nextPendingConnection();

		conn->write(name.toAscii().data());	//write the name of the session to initiate

		//NEED TO SEND OUT USERS & DOCS HERE


		//connect statements

		connect(conn, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
		connections.append(conn);
	}
}

/**
  *	Recieve a message and process it, then send it back out to everyone
  */
void Server::receiveMessage()
{
	foreach (QTcpSocket *socket, connections)
	{
		if (socket->bytesAvailable())
		{
			QByteArray rawMsg = socket->readAll();

			foreach (QTcpSocket *socket, connections)
			{
				socket->write(rawMsg);
			}
		}
	}
}
